﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Windows.Forms;
using System.Collections.Generic;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Collections.Specialized;
using System.Security.Permissions;

using Microsoft.BusinessData;
using BdcAdmin = Microsoft.SharePoint.BusinessData.Administration;
using Microsoft.Office.Server.Utilities;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.BusinessData.SharedService;
using Microsoft.SharePoint.BusinessData.MetadataModel;

namespace InstanceSiteVSTemplateWizard
{
    static class Program
    {
        private struct Constants
        {
            internal const string BusinessDataItemBuilder = "BusinessDataItemBuilder";
            internal const string BDWPItem = "BDWP Item";
            internal const string BDWPRelatedItems = "BDWP Related Items";
            internal const string BDWPRow = "BDWP Row";
            internal const string startBlock = "__BEGIN123xyz";
            internal const string endBlock = "__END123xyz";
        }

        public static String URL;
        public static String instanceTemplateName;
        public static EntityCenterInputForm[] inputForm = new EntityCenterInputForm[10];
        public static int j = 0;
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            
            String fileName;
            StringBuilder strb = new StringBuilder();
          
            string[] entityNames = new string[10];

            if (args.Length >= 2)
            {
                fileName = args[0];
                URL = args[1];
            }
            else
            {
                fileName = Path.Combine(Path.GetTempPath(), "Temp.txt");
                URL = @"http://" + System.Environment.MachineName.ToLower() + @"/";
            }



            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            int templateID =0;

            /* show the wizard forms for selecting webparts and details*/
            do
            {
                inputForm[j] = new EntityCenterInputForm(entityNames,j);
                
                Application.Run(inputForm[j]);


               /* if ISV selected action webpart and check box is disabled, means we don't want to show  form for adding webparts */
                if (inputForm[j].webpartTypeCode == EntityCenterInputForm.WebpartTypeCodes.BusinessDataActions)
                {
                    if (!inputForm[j].checkBox1.Checked)
                    {
                        j++; 
                        break;
                    }
                }
                    /* if the webpart type is businessdataitem, then we are asking user to replace the templatename in bdc model.
                     * if use checked the checkbox, we will write the template name otherwise we will write 'none' in the file */
                else if (inputForm[j].webpartTypeCode == EntityCenterInputForm.WebpartTypeCodes.BusinessDataItem)
                {
                    if (j == 0)
                    {
                        
                        templateID = getUniqueTemplateID();
                        if (inputForm[j].checkBox1.Checked)
                        {
                            instanceTemplateName = inputForm[j].entityNameproperty + "InstanceTemplate";
                        }
                        else
                        {
                            instanceTemplateName = "none";
                        }
                    }
                   
                }
                /* if ISV selected other than the action webpart and check box is disabled, 
                 * means we don't want to show  form for adding webparts */
                if (inputForm[j].webpartTypeCode != EntityCenterInputForm.WebpartTypeCodes.BusinessDataActions)
                {
                    if (!inputForm[j].detailsInputForm.checkBox1.Checked)
                    {
                        j++;
                        break;
                    }
                }

             /* building the entityanmes which are selected by the ISV, this information will be consumed, 
              * when we are showing associated entities  */
                 for (int k = 0; k < 10; k++)
                 {
                     if (entityNames[k] == null)
                     {
                         entityNames[k] = inputForm[j].entityNameproperty;
                         break;
                     }
                     else if (entityNames[k].ToString().CompareTo(inputForm[j].entityNameproperty) == 0)
                         break;
                 }

                 j++;
                /* we are just allowing adding 10 webparts only by ISV */
                 if (j == 10)
                     break;
               
            }
            while (true);

          
            strb.AppendLine(templateID.ToString());
            strb.AppendLine(instanceTemplateName);
            for (int l = 0; l < j; l++)
            {
                if (inputForm[l] == null)
                    break;

                strb.AppendLine(inputForm[l].webpartTypeCode.ToString());
                /* depending on webpart type, we are writig corresponding information to the file */
                switch (inputForm[l].webpartTypeCode)
                {
                    case EntityCenterInputForm.WebpartTypeCodes.BusinessDataActions:
                       strb.AppendLine(inputForm[l].entityNameproperty);
                       strb.AppendLine(inputForm[l].entityNameSpaceproperty);
                       strb.AppendLine(inputForm[l].lobSystempInstanceroperty);
                        break;

                    case EntityCenterInputForm.WebpartTypeCodes.BusinessDataItem:
                          strb.AppendLine(inputForm[l].entityNameproperty);
                          strb.AppendLine(inputForm[l].entityNameSpaceproperty);
                          strb.AppendLine(inputForm[l].lobSystempInstanceroperty);
                          strb.AppendLine(inputForm[l].specificFinderproperty);

                          strb.AppendLine(Constants.startBlock);
                          strb.AppendLine(inputForm[l].detailsInputForm.entitydeselectedfieldsproperty);
                          strb.AppendLine(Constants.endBlock);

                          strb.AppendLine(Constants.startBlock);
                          strb.AppendLine(inputForm[l].detailsInputForm.entityselectedfieldsproperty);
                          strb.AppendLine(Constants.endBlock);

                          strb.AppendLine(Constants.startBlock);
                          strb.AppendLine(inputForm[l].detailsInputForm.entityfieldsproperty1);
                          strb.AppendLine(Constants.endBlock);

                          strb.AppendLine(Constants.startBlock);
                          strb.AppendLine(inputForm[l].detailsInputForm.entityfieldsproperty2);
                          strb.AppendLine(Constants.endBlock);
                        break;

                    case EntityCenterInputForm.WebpartTypeCodes.BusinessDataList:
                          strb.AppendLine(inputForm[l].entityNameproperty);
                          strb.AppendLine(inputForm[l].entityNameSpaceproperty);
                          strb.AppendLine(inputForm[l].lobSystempInstanceroperty);
                          strb.AppendLine(Constants.startBlock);
                          strb.AppendLine(inputForm[l].detailsInputForm.entityselectedfieldsproperty);
                          strb.AppendLine(Constants.endBlock);

                          strb.AppendLine(Constants.startBlock);
                          strb.AppendLine(inputForm[l].detailsInputForm.entityfieldsproperty1);
                          strb.AppendLine(Constants.endBlock);

                          strb.AppendLine(Constants.startBlock);
                          strb.AppendLine(inputForm[l].detailsInputForm.entityfieldsproperty3);
                          strb.AppendLine(Constants.endBlock);

                          strb.AppendLine(Constants.startBlock);
                          strb.AppendLine(inputForm[l].detailsInputForm.entityfieldsproperty4);
                          strb.AppendLine(Constants.endBlock);
                        break;

                    case EntityCenterInputForm.WebpartTypeCodes.BusinessDataRelatedList:
                          strb.AppendLine(inputForm[l].entityNameproperty);
                          strb.AppendLine(inputForm[l].entityNameSpaceproperty);
                          strb.AppendLine(inputForm[l].lobSystempInstanceroperty);
                          strb.AppendLine(inputForm[l].AssociatedentityNameproperty);
                          strb.AppendLine(getConnPropertyDetails(inputForm[l].AssociatedentityNameproperty));                       

                          strb.AppendLine(Constants.startBlock);
                          strb.AppendLine(inputForm[l].detailsInputForm.entityselectedfieldsproperty);
                          strb.AppendLine(Constants.endBlock);

                          strb.AppendLine(Constants.startBlock);
                          strb.AppendLine(inputForm[l].detailsInputForm.entityfieldsproperty1);
                          strb.AppendLine(Constants.endBlock);

                          strb.AppendLine(Constants.startBlock);
                          strb.AppendLine(inputForm[l].detailsInputForm.entityfieldsproperty3);
                          strb.AppendLine(Constants.endBlock);

                          strb.AppendLine(Constants.startBlock);
                          strb.AppendLine(inputForm[l].detailsInputForm.entityfieldsproperty4);
                          strb.AppendLine(Constants.endBlock);
                        break;

                    case EntityCenterInputForm.WebpartTypeCodes.RelatedDocumentList:
                          strb.AppendLine(inputForm[l].entityNameproperty);
                          strb.AppendLine(inputForm[l].entityNameSpaceproperty);
                          strb.AppendLine(inputForm[l].lobSystempInstanceroperty);
                          strb.AppendLine(inputForm[l].specificFinderproperty);
                          strb.AppendLine(inputForm[l].AssociatedentityNameproperty);
                          strb.AppendLine(getConnPropertyDetails(inputForm[l].AssociatedentityNameproperty));                   

                          strb.AppendLine(Constants.startBlock);
                          strb.AppendLine(inputForm[l].detailsInputForm.entityselectedfieldsproperty);
                          strb.AppendLine(Constants.endBlock);

                          strb.AppendLine(Constants.startBlock);
                          strb.AppendLine(inputForm[l].detailsInputForm.entityfieldsproperty1);
                          strb.AppendLine(Constants.endBlock);

                          strb.AppendLine(Constants.startBlock);
                          strb.AppendLine(inputForm[l].detailsInputForm.entityfieldsproperty3);
                          strb.AppendLine(Constants.endBlock);

                          strb.AppendLine(Constants.startBlock);
                          strb.AppendLine(inputForm[l].detailsInputForm.entityfieldsproperty4);
                          strb.AppendLine(Constants.endBlock);
                        break;


                }
            }

            string[] str = new string[1];
            str[0] = strb.ToString();
            File.WriteAllLines(fileName, str);

        }
        
        /* if webpart is associated to the item, then we are returning "BDWP item" otherwise "BDWP row" */
        /* this information will be consumed while creating connection property for this webpart*/
       static string getConnPropertyDetails(string AssociatedentityNameproperty)
       {
           for (int l = 0; l < 10; l++)
            {
                if (inputForm[l] == null)
                    break;
                if (inputForm[l].entityNameproperty.CompareTo(AssociatedentityNameproperty) == 0)
                {
                    if (inputForm[l].webpartTypeCode == EntityCenterInputForm.WebpartTypeCodes.BusinessDataItem)
                        return Constants.BDWPItem;
                    else
                        return Constants.BDWPRow;

                }
           }
           return null;
       }

       /* the Following Function returns the Unique tempalte ID. the ID will be greater then 10050 */
       /* 14483 is sharepoint standard tempalteID */

 
        static int getUniqueTemplateID()
        {
            SPSite site = new SPSite(URL);
            SPWebTemplateCollection wtcoll = site.GetWebTemplates(1033);
            int ID = 10050;        

            foreach (SPWebTemplate wt in wtcoll)
            {
               
                if (ID < wt.ID && wt.ID != 14483)
                    ID = wt.ID;
            }            
          
            return ID + 1;
        }
    }
}
